package com.ujiuye.controller;

import com.ujiuye.pojo.Setmeal;
import com.ujiuye.service.ISetmealService;
import com.ujiuye.utils.*;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 套餐-一个套餐有多个检查组 前端控制器
 * </p>
 *
 * @author zhangwenping
 * @since 2021-07-05
 */
@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Reference  //RPC 远程调用 代理模式
    private ISetmealService setmealService;
    /*
    redisTemplate 默认调用jdk序列化器（存对象时）
    template    不会默认调用jdk序列化器（存字符串时）
     */
    @Resource
    private RedisTemplate<String,String> template;

    @PostMapping("/list")
    @PreAuthorize("hasAnyAuthority('SETMEAL_QUERY')")
    public PageResult list(@RequestBody QueryPageBean queryPageBean){
        try {
            return setmealService.listPage(queryPageBean);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Value("${uploadPath}")
    private String path;

    @PostMapping("/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile multipartFile){
        File file = MyFileUtils.upload(multipartFile, path);
        if (file != null){
            //file.getName() 存到redis中
            SetOperations<String, String> opsForSet = template.opsForSet();
            opsForSet.add("SETMEAL_PIC_UPLOAD",file.getName());
            return new Result(true, MessageConstant.UPLOAD_FILE_SUCCESS,file.getName());
        }
        return new Result(false, MessageConstant.UPLOAD_FILE_FAIL);
    }

    @PostMapping
    @PreAuthorize("hasAnyAuthority('SETMEAL_ADD')")
    public Result save(@RequestBody Setmeal setmeal,Integer[] checkgroupIds){
        try {
            setmealService.save(setmeal,checkgroupIds);
            //setmeal.getImg() 存到redis中
            SetOperations<String, String> opsForSet = template.opsForSet();
            String img = setmeal.getImg().substring(setmeal.getImg().lastIndexOf("/")+1);
            opsForSet.add("SETMEAL_PIC_DB",img);
            return new Result(true, MessageConstant.ADD_CHECKGROUP_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_CHECKGROUP_FAIL);
        }
    }

    @GetMapping("/save/{id}")//通过id查询检查项
    @PreAuthorize("hasAnyAuthority('SETMEAL_QUERY')")
    public Result getById(@PathVariable("id") int id){
        try {
            return setmealService.getById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_CHECKGROUP_FAIL);
        }
    }

    @PutMapping
    @PreAuthorize("hasAnyAuthority('SETMEAL_EDIT')")
    public Result update(@RequestBody Setmeal setmeal,Integer[] checkgroupIds){
        try {
            setmealService.update(setmeal,checkgroupIds);
            return new Result(true, MessageConstant.EDIT_CHECKGROUP_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_CHECKGROUP_FAIL);
        }
    }


    @DeleteMapping("/delete/{id}")
    @PreAuthorize("hasAnyAuthority('SETMEAL_DELETE')")
    public Result remove(@PathVariable("id") int id){
        try {
            setmealService.removeById(id);
            return new Result(true, MessageConstant.DELETE_CHECKGROUP_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.DELETE_CHECKGROUP_FAIL);
        }
    }

    @RequestMapping("/downloadexcel")
    public ResponseEntity<byte[]> downloadexcel() throws IOException {
        //后台查询全部套餐信息
        List<Setmeal> list = setmealService.list();
        //将套餐信息写入excel文件中
        File file = ListToExcel(list);
        //下载到客户端电脑
        return MyFileUtils.download(file);
    }

    //将集合数据写到excel文件中
    private File ListToExcel(List<Setmeal> list){
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("套餐信息");
        //设置表头
        HSSFRow headRow = sheet.createRow(0);
        //设置单元格
        headRow.createCell(0).setCellValue("编码");
        headRow.createCell(1).setCellValue("助记码");
        headRow.createCell(2).setCellValue("性别");
        headRow.createCell(3).setCellValue("年龄");
        headRow.createCell(4).setCellValue("价格");
        headRow.createCell(5).setCellValue("备注");
        headRow.createCell(6).setCellValue("名称");
        //遍历集合，将集合数据写入excel文件中
        for (int i=0;i<list.size();i++){
            HSSFRow row = sheet.createRow(i + 1);
            Setmeal setmeal = list.get(i);
            row.createCell(0).setCellValue(setmeal.getCode());
            row.createCell(1).setCellValue(setmeal.getHelpcode());
            String sex = "不限";
            if (setmeal.getSex().equals("1")){
                sex = "男";
            }
            if (setmeal.getSex().equals("2")){
                sex = "女";
            }
            row.createCell(2).setCellValue(sex);
            row.createCell(3).setCellValue(setmeal.getAge());
            row.createCell(4).setCellValue(setmeal.getPrice());
            row.createCell(5).setCellValue(setmeal.getRemark());
            row.createCell(6).setCellValue(setmeal.getName());
        }
        File file = new File(path+"套餐信息.xls");
        try {
            workbook.write(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }


}

